using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChatInGameUIMessageScroll : MonoBehaviour
{
	public MyUIInput newMessageInput;

	public UIButton sendButton;

	public ChatInGameUIChatMessage messageExample;

	public Transform messagesContainer;

	private void OnEnable()
	{
		sendButton.isEnabled = true;
	}

	public void SendNewMessage()
	{
		if (!string.IsNullOrEmpty(newMessageInput.value) && sendButton.isEnabled)
		{
			string polevvoda = new ChatMessageChecker().Check(newMessageInput.value);
			ChatController.thisScript.postMessageToChat(polevvoda, TDMController.myTeam, ChatWindow.instance.IdChat);
			sendButton.isEnabled = false;
			StartCoroutine(CallWithDelay(delegate
			{
				sendButton.isEnabled = true;
			}, 1f));
			newMessageInput.value = string.Empty;
		}
	}

	public void AddMessageToScroll(string text, bool isMine, PunTeams.Team team, ChatWindow.IdChatType idChat)
	{
		ChatInGameUIChatMessage chatInGameUIChatMessage = UnityEngine.Object.Instantiate(messageExample);
		chatInGameUIChatMessage.transform.SetParent(messagesContainer.transform);
		chatInGameUIChatMessage.transform.localScale = Vector3.one;
		chatInGameUIChatMessage.transform.localPosition = Vector3.one * 10000f;
		chatInGameUIChatMessage.SetMessageUI(isMine, text, TDMController.myTeam, team);
		chatInGameUIChatMessage.gameObject.SetActive(idChat == ChatWindow.instance.IdChat);
		List<ChatInGameUIChatMessage> messages = ChatInGameMessageStorage.getMessages(idChat);
		messages.Insert(0, chatInGameUIChatMessage);
		if (base.isActiveAndEnabled)
		{
			StartCoroutine(SetOffsetMessagesCoroutine(messages));
		}
	}

	public void SwitchChat(ChatWindow.IdChatType idChat)
	{
		foreach (ChatWindow.IdChatType item in ChatInGameMessageStorage.GetKesy())
		{
			foreach (ChatInGameUIChatMessage message in ChatInGameMessageStorage.getMessages(item))
			{
				message.gameObject.SetActive(item == idChat);
			}
		}
		if (base.isActiveAndEnabled)
		{
			StartCoroutine(SetOffsetMessagesCoroutine(ChatInGameMessageStorage.getMessages(idChat)));
		}
	}

	private IEnumerator SetOffsetMessagesCoroutine(List<ChatInGameUIChatMessage> allMessages)
	{
		yield return null;
		float currentOffset = 0f;
		foreach (ChatInGameUIChatMessage oldMessage in allMessages)
		{
			oldMessage.transform.localPosition = new Vector3(oldMessage.transform.localPosition.x, currentOffset, 0f);
			currentOffset = ((!oldMessage.isMine) ? (currentOffset + (float)oldMessage.otherMessageBG.height) : (currentOffset + (float)oldMessage.myMessageBG.height));
		}
	}

	private IEnumerator CallWithDelay(Action action, float delay)
	{
		yield return new WaitForSeconds(delay);
		action();
	}
}
